package org.xxpay.pay.channel.ywxpay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.entity.WxUser;
import org.xxpay.pay.service.CommonService;

import java.util.Date;

/**
 * @Description: 处理微信服务端MQ消息
 */
@Component
public class YwxpayMqNotify {

    private static final MyLog _log = MyLog.getLog(YwxpayMqNotify.class);

    @Autowired
    private CommonService commonService;

    @JmsListener(destination = YwxpayConfig.WX_NOTIFY_QUEUE_NAME)
    @Async("mqExecutor")
    public void receive(String msg) {
        String logPrefix = "【WX通知】";
        _log.info("{}接收消息:msg={}", logPrefix, msg);
        JSONObject msgObj = JSON.parseObject(msg);
        String randomId = msgObj.getString("randomId");
        String type = msgObj.getString("type");
        JSONObject data = msgObj.getJSONObject("data");
        // type : 1-用户登录状态,2-支付消息
        // data : {loginStatus:1, loginResult:""}
        if("1".equals(type)) {
            Integer loginStatus = data.getInteger("loginStatus");
            String loginResult = data.getString("loginResult");
            String loginData = data.getString("loginData");
            String wxId = data.getString("wxId");
            String wxNickName = data.getString("wxNickName");
            WxUser wxUser = new WxUser();
            wxUser.setLoginStatus(loginStatus);
            wxUser.setLoginResult(loginResult);
            wxUser.setWxDat(loginData);
            wxUser.setWxId(wxId);
            wxUser.setNickName(wxNickName);
            wxUser.setLoginSyncTime(new Date());
            int updateCount = commonService.wxUserService.updateByRandomId(wxUser, randomId);
            _log.info("{}更新微信用户登录状态,返回结果:{}", logPrefix, updateCount);
        }

    }

}
